package com.lab.utils;

import android.content.Context;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.lab.rtenvironment.AppCoreRuntime;

/**
 * Created by ak
 * Toast工具类
 */
public class ToastUtil {

    private static Toast sToastMutex;

    public static void toast(int msgResId) {
        toast(AppCoreRuntime.context, msgResId, Toast.LENGTH_SHORT);
    }

    public static void toast(String msg) {
        toast(AppCoreRuntime.context, msg, Toast.LENGTH_SHORT);
    }

    public static void toast(Context context, int msgResId, int duration) {
        toast(context, msgResId, duration, Gravity.CENTER, 0, 0);
    }

    public static void toast(Context context, String msg, int duration) {
        toast(context, msg, duration, Gravity.CENTER, 0, 0);
    }

    public static void toastNormal(int msgResId) {
        if (isOnMainThread()) {
            Toast.makeText(AppCoreRuntime.context,msgResId,Toast.LENGTH_SHORT).show();
        }
    }

    public static void toast(Context context, int msgResId, int duration, int gravity, int offsetX, int offsetY) {
        if (null != context && isOnMainThread()) {
            Toast toast = Toast.makeText(context, msgResId, duration);
            toast.setGravity(gravity, offsetX, offsetY);
            toast.show();
        }
    }

    public static void toast(Context context, String msg, int duration, int gravity, int offsetX, int offsetY) {
        if (null != context && null != msg && isOnMainThread()) {
            Toast toast = Toast.makeText(context, msg, duration);
            toast.setGravity(gravity, offsetX, offsetY);
            toast.show();
        }
    }

    public static void toastMutex(int msgResId) {
        toastMutex(AppCoreRuntime.context, msgResId, Toast.LENGTH_SHORT, Gravity.CENTER, 0, 0);
    }

    public static void toastMutex(String msg) {
        toastMutex(AppCoreRuntime.context, msg, Toast.LENGTH_SHORT, Gravity.CENTER, 0, 0);
    }

    public static void toastMutex(Context context, int msgResId, int duration, int gravity, int offsetX, int offsetY) {
        if (null != context && isOnMainThread()) {
            if (null != sToastMutex) sToastMutex.cancel();
            sToastMutex = Toast.makeText(context, msgResId, duration);
            sToastMutex.setGravity(gravity, offsetX, offsetY);
            sToastMutex.show();
        }
    }

    public static void toastMutex(Context context, String msg, int duration, int gravity, int offsetX, int offsetY) {
        if (null != context && null != msg && isOnMainThread()) {
            if (null != sToastMutex) sToastMutex.cancel();
            sToastMutex = Toast.makeText(context, msg, duration);
            sToastMutex.setGravity(gravity, offsetX, offsetY);
            sToastMutex.show();
        }
    }

    private static boolean isOnMainThread() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            return false;
        }
        return true;
    }

}
